package com.tingyuge.thinking.spring.configuration.metadata;

import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/8/22
 */
@PropertySource("classpath:/META-INF/user-bean-definitions.properties")
public class PropertySourceDemo {

    @Bean
    public User user(@Value("${user.id}" ) Long id, @Value("${user.name}" )String name){
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }

    public static void main(String[] args) {


        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //添加一個propertySource
        HashMap<String, Object> propertiesSouce = new HashMap<>();
        propertiesSouce.put("user.name", "first");
        MapPropertySource mapPropertySource = new MapPropertySource("fisrt-proproty-source", propertiesSouce);
        applicationContext.getEnvironment().getPropertySources().addFirst(mapPropertySource);
        //注册当前类作为Configuration class
        applicationContext.register(PropertySourceDemo.class);
        applicationContext.refresh();
        Map<String, User> userMap = applicationContext.getBeansOfType(User.class);

        for (Map.Entry<String, User> stringUserEntry : userMap.entrySet()) {
            System.out.printf(" User bean name %s  value: %s \n", stringUserEntry.getKey(), stringUserEntry.getValue());
        }
        System.out.println(applicationContext.getEnvironment().getPropertySources());
        applicationContext.close();
    }
}
